let modelDomain; // V1.1-V3.5动态获取，高于以上版本手动指定

var total_res = "";
let disabled = ref(false);
let text = ref([]);
// -- 对话数组
let list = ref([
  {
    left: false,
    message: "可以聊天了~",
  },
]);

//--机器人回答的内容
let bigModel = ref({});
// // 控制对话框的关闭
let ttsWSRef = ref({});

// 聊天框滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const chat = document.querySelector(".chandler-content_main-board");
    //   console.log(chat.scrollHeight);
    if (chat) {
      chat.scrollTop = chat.scrollHeight;
      window.scroll(0, chat.scrollHeight + 50);
    }
  });
};

const btnIsDisabled = () => {
  disabled.value = false;

  list.value[list.value.length - 1].tips = false;
};


const stopAnswer = () => {
  ttsWSRef.value.close()
  // 隐藏
  btnIsDisabled()
}


export const chatHooks = () => {


  onMounted(() => {
    class TTSRecorder {
      // constructor({ appId = APPID } = {}) {
      //   this.appId = appId;
      //   this.status = "init";
      // }

      constructor({ } = {}) {
        this.status = "init";
      }

      // 修改状态
      setStatus(status) {
        this.onWillStatusChange && this.onWillStatusChange(this.status, status);
        this.status = status;
      }

      // // 连接websocket  inpMessage 文本框的值
      // connectWebSocket(inpMessage) {
      //   this.setStatus("ttsing");
      //   return getWebsocketUrl().then((url) => {
      //     let ttsWS;
      //     if ("WebSocket" in window) {
      //       ttsWS = new WebSocket(url);
      //     } else if ("MozWebSocket" in window) {
      //       ttsWS = new MozWebSocket(url);
      //     } else {
      //       alert("浏览器不支持WebSocket");
      //       return;
      //     }
      //     this.ttsWS = ttsWS;
      //     ttsWSRef.value = ttsWS;
      //     ttsWS.onopen = (e) => {
      //       // 文本框的值
      //       this.webSocketSend(inpMessage);
      //     };
      //     ttsWS.onmessage = (e) => {
      //       // console.log(e.data,'==onmessage==')
      //       this.result(e.data);
      //     };
      //     ttsWS.onerror = (e) => {
      //       clearTimeout(this.playTimeout);
      //       this.setStatus("error");
      //       alert("WebSocket报错，请f12查看详情");
      //       console.error(
      //         `详情查看：${encodeURI(url.replace("wss:", "https:"))}`
      //       );
      //     };
      //     ttsWS.onclose = (e) => {
      //       console.log(e);
      //     };
      //   });
      // }

      // // websocket发送数据
      // webSocketSend(inpMessage) {
      //   var params = {
      //     header: {
      //       app_id: this.appId,
      //       uid: "fd3f47e4-d",
      //     },
      //     parameter: {
      //       chat: {
      //         domain: modelDomain,
      //         temperature: 0.5,
      //         max_tokens: 1024,
      //       },
      //     },
      //     payload: {
      //       message: {
      //         text: text.value,
      //       },
      //     },
      //   };

      //   this.ttsWS.send(JSON.stringify(params));
      // }

      start(message) {
        total_res = ""; // 请空回答历史
        this.connectWebSocket(message);
      }

      // websocket接收数据的处理
      result(resultData) {
        let jsonData = JSON.parse(resultData);
        alert(resultData)
        console.log(`output->jsonData`, jsonData)
        let content = jsonData.payload?.choices?.text[0].content;
        console.log(jsonData.payload?.choices?.text[0].content);
        total_res += content;
        // xfa-1: 注释
        // $("#output_text").val(total_res);
        // console.log(resultData)
        // 提问失败

        list.value[list.value.length - 1].message += content;

        console.log(`output->list.value[list.value.length - 1].message`, list.value[list.value.length - 1].message)
        scrollToBottom();
        if (jsonData.header.code !== 0) {
          btnIsDisabled();
          alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
          console.error(`${jsonData.header.code}:${jsonData.header.message}`);
          return;
        }
        if (jsonData.header.code === 0 && jsonData.header.status === 2) {
          text.value.push({
            role: "system",
            content: this.message,
          });

          btnIsDisabled();
          this.ttsWS.close();
          bigModel.value.setStatus("init");
        }
      }
    }

    bigModel.value = new TTSRecorder();

    bigModel.value.onWillStatusChange = function (oldStatus, status) {
      console.log(`output->oldStatus, status`, oldStatus, status);
    };
  });

  return {
    text,
    list,
    scrollToBottom,
    disabled,
    stopAnswer,
    bigModel
  };
};
